package me.duzhi.ilog.cms.plugins.compress;

import com.jfinal.kit.StrKit;
import freemarker.core.Environment;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.*;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author ashang.peng@aliyun.com
 * @date 一月 07, 2017
 */

public class CompressDirective implements TemplateDirectiveModel {
    @SuppressWarnings("rawtypes")
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
            throws TemplateException, IOException {

        Object var = params.get("var");
        if (var == null) {
            throw new TemplateModelException("assets tag attribute var can not be null!");
        }
        String varName = var.toString();
        if (StrKit.isBlank(varName)) {
            throw new TemplateModelException("assets tag attribute var can not be null!");
        }
        Object file = params.get("file");
        if (file == null) {
            throw new TemplateModelException("assets tag attribute file can not be null!");
        }

        String fileName = file.toString();
        if (StrKit.isBlank(fileName)) {
            throw new TemplateModelException("assets tag attribute file can not be null!");
        }
        Object ido = params.get("id");
        if (ido == null) {
            throw new TemplateModelException("assets tag attribute id can not be null!");
        }
        String id = ido.toString();
        if (StrKit.isBlank(id)) {
            throw new TemplateModelException("assets tag attribute id can not be null!");
        }

        List<String> path = CompressKit.getPath(id, fileName);

        BeansWrapper beansWrapper = new BeansWrapperBuilder(Configuration.getVersion()).build();
        for (String s : path) {
            env.setVariable(varName, beansWrapper.wrap(s));
            body.render(env.getOut());
        }
    }
}
